<?php
namespace app\api\model;

use think\Model;
use think\exception\ValidateException;

class OrderDada extends Model
{
    protected $name = 'order_dada';
    
    protected $autoWriteTimestamp = true;

    // 达达订单状态
    const STATUS_ORDER_DISPATCH = 1;
    const STATUS_ORDER_PICKUPING = 2;
    const STATUS_ORDER_DELIVERY = 3;
    const STATUS_ORDER_COMPLETED = 4;
    const STATUS_ORDER_CANCELLED = 5;

    const STATUS_ORDER_ASSIGN = 8;
    const STATUS_ORDER_ABNORMAL_MIDWAY = 9;
    const STATUS_ORDER_ABNORMAL_COMPLETED = 10;
    const STATUS_ORDER_REACH = 100;
    const STATUS_ORDER_ERROR = 1000;

    public static function statusOrderList()
    {
        return [
            self::STATUS_ORDER_DISPATCH => '待接单',
            self::STATUS_ORDER_PICKUPING => '待取货',
            self::STATUS_ORDER_DELIVERY => '配送中',
            self::STATUS_ORDER_COMPLETED => '已完成',
            self::STATUS_ORDER_CANCELLED => '已取消',

            self::STATUS_ORDER_ASSIGN => '指派单',
            self::STATUS_ORDER_ABNORMAL_MIDWAY => '妥投异常之物品返回中',
            self::STATUS_ORDER_ABNORMAL_COMPLETED => '妥投异常之物品返回完成',
            self::STATUS_ORDER_REACH=> '骑士到店',
            self::STATUS_ORDER_ERROR => '创建达达运单失败',
        ];
    }

    /**
     * 订单新增
     */
    public function ddOrderCreate($param)
    {
        // 验证数据
        try {
            validate([
                'appid'  => 'require', 
                'third_number'  => 'require', 
                'app_type'  => 'require', 
            ])->message([
                'appid.require'  => 'appid必须传递',   
                'third_number.require'  => 'third_number必须传递',   
                'app_type.require'  => 'app_type必须传递',   
            ])->check($param);
        } catch (ValidateException $e) {
            return result_error($e->getError());
        }
        
        $data['appid'] = $param['appid'] ?? '';//appid
        $data['third_number'] = $param['third_number'] ?? '';//配送平台订单号
        $data['sys_number'] = $param['sys_number']??'';//骑手系统订单号(系统生成)
        $data['call_number'] = $param['call_number'] ?? '';//调用方订单号
        $data['app_type'] = $param['app_type'] ?? 0;//第三方平台类型 1:闪送, 2:达达,3:蜂鸟

        $data['appoint_type'] =  $param['appoint_type'] ?? 0;//0:立即单, 1:预约单
        $data['appointment_date'] =  $param['appointment_date'] ?? '';//预约取件时间
        $data['expect_receive_time'] =  $param['expect_receive_time'] ?? '';//期望送达时间
        $data['store_id'] = $param['store_id'] ?? '';//配送店铺ID


        $data['distance'] = $param['distance'] ?? 0;//配送距离(单位：米)
        $data['deliverFee'] =$param['deliverFee']?? 0;//运费(单位：分)
        $data['couponFee'] =$param['couponFee']?? 0;//优惠券费用(单位：分)
        $data['tips'] =$param['tips']?? 0;//小费（单位：分，精确小数点后一位，小费金额不能高于订单金额。）
        $data['fee'] =  $param['fee']?? 0;//实际运费(单位：分，运费减去优惠券费用
        $data['insuranceFee'] =$param['insuranceFee']?? 0;//保价费(单位：分)

        // 创建
        try {
            $result = $this->save($data);

            if ($result) {
                return result_success('success', $data);
            } else {
                return result_error('保存失败');
            }
        } catch (\Exception $e) {
            return result_error($e->getMessage());
        }
    }


    /**
     * 订单更新
     */
    public function ddOrderUpdate($param)
    {
        if (empty($param['third_number'])&&empty($param['sys_number'])&&empty($param['call_number'])&&empty($param['id'])){
                return  result_error('缺少必要更新条件');
        }
     
        if(isset($param['status'])) $data['status'] = $param['status'];//订单状态 {select} (1:待接单,2:待取货,3:配送中,4:已完成,5:已取消, 8:指派单,9:妥投异常之物品返回中, 10:妥投异常之物品返回完成, 100:骑士到店,1000:创建达达运单失败)

        try {
           
            $find = $this
                    ->when(isset($param['third_number']),function ($query) use($param) {
                        $query->where('third_number', $param['third_number']);
                    })
                    ->when(isset($param['sys_number']),function ($query) use($param) {
                        $query->where('sys_number', $param['sys_number']);
                    })
                    ->when(isset($param['call_number']),function ($query) use($param) {
                        $query->where('call_number', $param['call_number']);
                    })
                    ->when(isset($param['id']),function ($query) use($param) {
                        $query->where('id', $param['id']);
                    })
                    ->find();
            if (!$find){
                 return  result_error('未查询到订单');
            }  
            
            $result=$find->save($data);

            if ($result) {
               return result_success('success',$result);
            } else {
               return result_error('保存失败');
            }
        } catch (\Exception $e) {
             return result_error($e->getMessage());
        }
    }


    /**
     * 订单加价
     */
   public function ddAdditionSave($param)
    {
        if (empty($param['third_number'])&&empty($param['sys_number'])&&empty($param['call_number'])&&empty($param['id'])){
                return  result_error('缺少必要更新条件');
        }

        try {
            validate([
                'addition_amount'  => 'require', //加价的金额（分）
            ])->message([
                'addition_amount.require'  => 'addition_amount必须传递',    
            ])->check($param);
        } catch (ValidateException $e) {
            return result_error($e->getError());
        }

        // 创建
        try {
              $find = $this
                    ->when(isset($param['third_number']),function ($query) use($param) {
                        $query->where('third_number', $param['third_number']);
                    })
                    ->when(isset($param['sys_number']),function ($query) use($param) {
                        $query->where('sys_number', $param['sys_number']);
                    })
                    ->when(isset($param['call_number']),function ($query) use($param) {
                        $query->where('call_number', $param['call_number']);
                    })
                    ->when(isset($param['id']),function ($query) use($param) {
                        $query->where('id', $param['id']);
                    })
                    ->find();
            if (!$find){
                 return  result_error('未查询到订单');
            }  

            $result=$find
                    ->setInc('fee', $param['addition_amount'])
                    ->setInc('deliverFee', $param['addition_amount'])
                    ->setInc('tips', $param['addition_amount']);

            if ($result) {
                return result_success('success',$result);
            } else {
                return result_error('保存失败');
            }
        } catch (\Exception $e) {
             return result_error($e->getMessage());
        }
    }
}